package org.ehe.erp.service.quality.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.ehe.business.bom.domain.BomMaster;
import org.ehe.business.bom.service.BomMasterService;
import org.ehe.business.monitor.MonitorMethod;
import org.ehe.business.overdue.config.OverdueStatus;
import org.ehe.business.overdue.extract.PurcharOrderDataExtractor;
import org.ehe.business.overdue.extract.QualityDataExtractor;
import org.ehe.business.overdue.extract.SolutionDataExtractor;
import org.ehe.business.overdue.util.FormatOverdueTimeUtil;
import org.ehe.business.timeout.contants.BizTypeConstant;
import org.ehe.business.timeout.domain.TimeoutInstance;
import org.ehe.business.timeout.mapper.TimeoutConfigMapper;
import org.ehe.business.timeout.service.TimeoutInstanceService;
import org.ehe.common.core.domain.dto.StartProcessDTO;
import org.ehe.common.core.domain.dto.StartProcessReturnDTO;
import org.ehe.common.core.service.WorkflowService;
import org.ehe.common.core.utils.MapstructUtils;
import org.ehe.common.mybatis.core.page.PageQuery;
import org.ehe.common.mybatis.core.page.TableDataInfo;
import org.ehe.common.satoken.utils.LoginHelper;
import org.ehe.common.sse.dto.SseMessageDto;
import org.ehe.common.sse.utils.SseMessageUtils;
import org.ehe.erp.constants.QualityTaskConstants;
import org.ehe.erp.domain.purchase.ErpPurchaseOrder;
import org.ehe.erp.domain.purchase.ErpPurchaseOrderItem;
import org.ehe.erp.domain.purchase.vo.ErpPurchaseOrderItemVo;
import org.ehe.erp.domain.quality.ErpQualityTask;
import org.ehe.erp.domain.quality.bo.ErpQualityTaskBo;
import org.ehe.erp.domain.quality.dto.QualityRecordQueryDto;
import org.ehe.erp.domain.quality.dto.QualityTaskQueryDto;
import org.ehe.erp.domain.quality.vo.ErpQualityRecordVo;
import org.ehe.erp.domain.quality.vo.ErpQualityTaskVo;
import org.ehe.erp.enums.ErpAuditStatus;
import org.ehe.erp.mapper.purchase.ErpPurchaseOrderItemMapper;
import org.ehe.erp.mapper.quality.ErpQualityTaskMapper;
import org.ehe.erp.service.purchase.IErpPurchaseOrderService;
import org.ehe.erp.service.quality.ErpQualityRecordService;
import org.ehe.erp.service.quality.ErpQualityTaskService;
import org.ehe.system.domain.vo.SysUserVo;
import org.ehe.system.service.ISysUserService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.support.TransactionSynchronizationAdapter;
import org.springframework.transaction.support.TransactionSynchronizationManager;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

/**
 * 质检任务服务实现
 *
 * @author zhangnn
 * @className ErpQualityTaskServiceImpl
 * @description 质检任务业务逻辑实现
 * @date 2025-09-11 15:00:00
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class ErpQualityTaskServiceImpl extends ServiceImpl<ErpQualityTaskMapper, ErpQualityTask>
    implements ErpQualityTaskService {

    private final ErpQualityTaskMapper baseMapper;
    private final TimeoutInstanceService timeoutInstanceService;
    private final BomMasterService bomMasterService;
    private final IErpPurchaseOrderService purchaseOrderService;
    private final ErpQualityRecordService qualityRecordService;
    private final ISysUserService userService;
    private final TimeoutConfigMapper timeoutConfigMapper;
    private final WorkflowService workflowService;

    /**
     * 分页查询质检任务列表
     * @param queryDto
     * @param pageQuery
     * @return
     */
    @Override
    public TableDataInfo<ErpQualityTaskVo> queryPageList(QualityTaskQueryDto queryDto, PageQuery pageQuery) {
        LambdaQueryWrapper<ErpQualityTask> wrapper = buildQueryWrapper(queryDto);
        IPage<ErpQualityTaskVo> page = baseMapper.selectVoPage(pageQuery.build(), wrapper);
        page.getRecords().forEach(p->{
            BomMaster bom = bomMasterService.getById(p.getBomId());
            if(Objects.nonNull(bom)){
                p.setBomName(bom.getBomName());
                p.setBomCode(bom.getBomCode());
            } else if(p.getBomId() == 0L){
                p.setBomCode("自主创建采购订单");
                p.setBomName("自主创建采购订单");
            }
        });
        return TableDataInfo.build(page);
    }

    /**
     * 查询质检任务列表
     * @param queryDto
     * @return
     */
    @Override
    public List<ErpQualityTaskVo> queryList(QualityTaskQueryDto queryDto) {
        LambdaQueryWrapper<ErpQualityTask> wrapper = buildQueryWrapper(queryDto);
        List<ErpQualityTask> list = baseMapper.selectList(wrapper);
        return MapstructUtils.convert(list, ErpQualityTaskVo.class);
    }

    /**
     * 根据ID查询质检任务
     * @param id
     * @return
     */
    @Override
    public ErpQualityTaskVo queryById(Long id) {
        return baseMapper.selectVoById(id);
    }

    /**
     * 新增质检任务
     * @param bo
     * @return
     */
    @Override
    //@MonitorMethod(bizType = "qualityOverdue", extractor = QualityDataExtractor.class)
    @Transactional(rollbackFor = Exception.class)
    public ErpQualityTask insertByBo(ErpQualityTaskBo bo) {
        // 校验任务单号唯一性
        if (StrUtil.isNotBlank(bo.getTaskNo()) && !checkTaskNoUnique(bo.getTaskNo(), null)) {
            throw new RuntimeException("质检任务单号已存在");
        }
        //待提交
        bo.setApproveStatus(String.valueOf(ErpAuditStatus.PENDING_SUBMIT.getStatus()));

        // 如果没有提供任务单号，自动生成
        if (StrUtil.isBlank(bo.getTaskNo())) {
            bo.setTaskNo(generateTaskNo());
        }

        ErpQualityTask entity = BeanUtil.toBean(bo, ErpQualityTask.class);
        validEntityBeforeSave(entity);
        // 响应
        entity.setIsOverdue("0");
        int hours = timeoutConfigMapper.getTimeByBizType(BizTypeConstant.QUALITY);
        entity.setIsOverdueEndTime(LocalDateTime.now().plusHours(hours));
        entity.setCreateBy(LoginHelper.getUsername());

        boolean flag = baseMapper.insert(entity) > 0;
        if (flag) {
            bo.setId(entity.getId());
        }
        return entity;
    }

    /**
     * 修改质检任务
     * @param bo
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean updateByBo(ErpQualityTaskBo bo) {
        // 校验任务单号唯一性
        if (StrUtil.isNotBlank(bo.getTaskNo()) && !checkTaskNoUnique(bo.getTaskNo(), bo.getId())) {
            throw new RuntimeException("质检任务单号已存在");
        }

        ErpQualityTask entity = BeanUtil.toBean(bo, ErpQualityTask.class);
        validEntityBeforeSave(entity);
        // 计算超时报警时间
//        if (entity.getTimeoutDuration() != null && entity.getTimeoutDuration() > 0) {
//            entity.setTimeoutAlarmTime(LocalDateTime.now().plusDays(entity.getTimeoutDuration()));
//        }
//        //时常
//        entity.setIsOverdue(OverdueStatus.PENDING);
//        int hours = timeoutConfigMapper.getTimeByBizType(BizTypeConstant.QUALITY);
//        entity.setIsOverdueEndTime(LocalDateTime.now().plusHours(hours));

        baseMapper.updateById(entity);

        return true;
    }

    /**
     * 校验并删除质检任务
     * @param ids
     * @param isValid
     * @return
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if (isValid) {
            // 检查是否存在进行中的任务
            for (Long id : ids) {
                ErpQualityTask task = baseMapper.selectById(id);
                if (task != null && task.getStatus() == 1) {
                    throw new RuntimeException("存在质检中的任务，无法删除");
                }
            }
        }
        return baseMapper.deleteBatchIds(ids) > 0;
    }

    /**
     * 校验任务单号是否唯一
     * @param taskNo
     * @param id
     * @return
     */
    @Override
    public Boolean checkTaskNoUnique(String taskNo, Long id) {
        LambdaQueryWrapper<ErpQualityTask> wrapper = Wrappers.<ErpQualityTask>lambdaQuery()
            .eq(ErpQualityTask::getTaskNo, taskNo);
        if (ObjectUtil.isNotNull(id)) {
            wrapper.ne(ErpQualityTask::getId, id);
        }
        return baseMapper.selectCount(wrapper) == 0;
    }

    /**
     * 分配指定人员
     * @param taskId
     * @param assignUserId
     * @param assignUserName
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public ErpQualityTask assignTask(Long taskId, Long assignUserId, String assignUserName) {
        ErpQualityTask task = baseMapper.selectById(taskId);
        if (task == null) {
            throw new RuntimeException("质检任务不存在");
        }

        if (task.getStatus() != 0) {
            throw new RuntimeException("只有待质检状态的任务才能分配");
        }

        LambdaUpdateWrapper<ErpQualityTask> wrapper = Wrappers.<ErpQualityTask>lambdaUpdate()
            .eq(ErpQualityTask::getId, taskId)
            .set(ErpQualityTask::getAssignUserId, assignUserId)
            .set(ErpQualityTask::getAssignUserName, assignUserName);

        if(null != assignUserId){
            task.setAssignUserId(assignUserId);
            task.setAssignUserName(assignUserName);
            task.setAssignStatus("1");
            task.setAssignTime(LocalDateTime.now());

            //修改响应状态和已分配人员的响应截止时间
            task.setIsOverdue(OverdueStatus.PENDING);
            int hours = timeoutConfigMapper.getTimeByBizType(BizTypeConstant.QUALITY);
            task.setIsOverdueEndTime(LocalDateTime.now().plusHours(hours));
            //等待责任人响应
            task.setApproveStatus(String.valueOf(ErpAuditStatus.WAITING.getStatus()));

            this.baseMapper.updateById(task);
            //启动流程
            StartProcessDTO process = new StartProcessDTO();
            Map<String,Object> map = new HashMap<>();
            map.put("type","qualityTask");
            map.put("engineer",assignUserId);
            process.setVariables(map);
            //BOM 完成审批流程
            process.setFlowCode("qualityTask");
            process.setBusinessId(String.valueOf(task.getId()));
            StartProcessReturnDTO processReturnDTO = workflowService.startWorkFlow(process);
            log.info("流程审批发起成功，已启动: taskId={}, engineerId={}", task.getId(), task.getCreateBy());
            workflowService.completeTask(processReturnDTO.getTaskId(),"采购订单【"+task.getOrderNo()+"】的质检任务");
        }
        return task;
    }

    /**
     * 开始质检
     * @param taskId
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean startQuality(Long taskId) {
        ErpQualityTask task = baseMapper.selectById(taskId);
        if (task == null) {
            throw new RuntimeException("质检任务不存在");
        }

        if (task.getStatus() != 0 && task.getApproveStatus().equals(ErpAuditStatus.APPROVE.getStatus())) {
            throw new RuntimeException("只有待质检且已审核通过状态的任务才能开始");
        }

        if (task.getAssignUserId() == null) {
            throw new RuntimeException("任务未分配给质检人员");
        }

        LocalDateTime now = LocalDateTime.now();
        LambdaUpdateWrapper<ErpQualityTask> wrapper = Wrappers.<ErpQualityTask>lambdaUpdate()
            .eq(ErpQualityTask::getId, taskId)
            // 分配的质检人员
            //.eq(ErpQualityTask::getAssignUserId,LoginHelper.getUserId())
            .set(ErpQualityTask::getStatus, 1)
            .set(ErpQualityTask::getStartTime, now);

        // 重新计算超时报警时间
        if (task.getTimeoutDuration() != null && task.getTimeoutDuration() > 0) {
            wrapper.set(ErpQualityTask::getTimeoutAlarmTime, now.plusMinutes(task.getTimeoutDuration()));
        }
        //录入或修改时效
        //this.insertTimeInstance(task);

        return baseMapper.update(null, wrapper) > 0;
    }

    /**
     * 完成质检
     * @param taskId 任务ID
     * @param qualityResult 质检结果 (2-质检完成, 3-质检不合格)
     * @param remark 备注
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean completeQuality(Long taskId, Integer qualityResult, String remark) {
        ErpQualityTask task = baseMapper.selectById(taskId);
        if (task == null) {
            throw new RuntimeException("质检任务不存在");
        }

        if (task.getStatus() != 1) {
            throw new RuntimeException("只有质检中的任务才能完成");
        }

        if (qualityResult != 2 && qualityResult != 3) {
            throw new RuntimeException("质检结果参数错误");
        }

        LambdaUpdateWrapper<ErpQualityTask> wrapper = Wrappers.<ErpQualityTask>lambdaUpdate()
            .eq(ErpQualityTask::getId, taskId)
            .set(ErpQualityTask::getStatus, qualityResult)
            .set(ErpQualityTask::getCompleteTime, LocalDateTime.now())
            .set(ErpQualityTask::getIsTimeout, 0); // 完成时清除超时标记

        if (StrUtil.isNotBlank(remark)) {
            wrapper.set(ErpQualityTask::getRemark, remark);
        }

        //录入或修改时效
        //this.insertTimeInstance(task);

        return baseMapper.update(null, wrapper) > 0;
    }

    /**
     * 暂停任务
     * @param taskId
     * @param remark
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean pauseTask(Long taskId, String remark) {
        ErpQualityTask task = baseMapper.selectById(taskId);
        if (task == null) {
            throw new RuntimeException("质检任务不存在");
        }

        if (task.getStatus() != 1) {
            throw new RuntimeException("只有质检中的任务才能暂停");
        }

        LambdaUpdateWrapper<ErpQualityTask> wrapper = Wrappers.<ErpQualityTask>lambdaUpdate()
            .eq(ErpQualityTask::getId, taskId)
            .set(ErpQualityTask::getStatus, 4);

        if (StrUtil.isNotBlank(remark)) {
            wrapper.set(ErpQualityTask::getRemark, remark);
        }

        return baseMapper.update(null, wrapper) > 0;
    }

    /**
     * 恢复任务
     * @param taskId
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean resumeTask(Long taskId) {
        ErpQualityTask task = baseMapper.selectById(taskId);
        if (task == null) {
            throw new RuntimeException("质检任务不存在");
        }

        if (task.getStatus() != 4) {
            throw new RuntimeException("只有暂停的任务才能恢复");
        }

        LocalDateTime now = LocalDateTime.now();
        LambdaUpdateWrapper<ErpQualityTask> wrapper = Wrappers.<ErpQualityTask>lambdaUpdate()
            .eq(ErpQualityTask::getId, taskId)
            .set(ErpQualityTask::getStatus, 1);

        // 重新计算超时报警时间
        if (task.getTimeoutDuration() != null && task.getTimeoutDuration() > 0) {
            wrapper.set(ErpQualityTask::getTimeoutAlarmTime, now.plusMinutes(task.getTimeoutDuration()));
        }
        // 修改时效信息
        this.insertTimeInstance(task);

        return baseMapper.update(null, wrapper) > 0;
    }

    /**
     * 根据批次ID查询质检任务
     * @param orderNo
     * @return
     */
    @Override
    public List<ErpQualityTaskVo> getByBatchId(Long orderNo) {
        LambdaQueryWrapper<ErpQualityTask> wrapper = Wrappers.<ErpQualityTask>lambdaQuery()
            .eq(ErpQualityTask::getOrderNo, orderNo)
            .orderByDesc(ErpQualityTask::getCreateTime);
        return baseMapper.selectVoList(wrapper);
    }

    /**
     * 获取待质检任务数量
     * @param assignUserId
     * @return
     */
    @Override
    public Integer getPendingTaskCount(Long assignUserId) {
        LambdaQueryWrapper<ErpQualityTask> wrapper = Wrappers.<ErpQualityTask>lambdaQuery()
            .eq(ErpQualityTask::getStatus, 0);

        if (assignUserId != null) {
            wrapper.eq(ErpQualityTask::getAssignUserId, assignUserId);
        }

        return Math.toIntExact(baseMapper.selectCount(wrapper));
    }

    /**
     * 获取超时任务列表
     * @return
     */
    @Override
    public List<ErpQualityTaskVo> getTimeoutTasks() {
        LambdaQueryWrapper<ErpQualityTask> wrapper = Wrappers.<ErpQualityTask>lambdaQuery()
            .in(ErpQualityTask::getStatus, 0, 1) // 待质检或质检中
            .le(ErpQualityTask::getTimeoutAlarmTime, LocalDateTime.now())
            .orderByAsc(ErpQualityTask::getTimeoutAlarmTime);
        return baseMapper.selectVoList(wrapper);
    }

    /**
     * 批量分配任务
     * @param taskIds
     * @param assignUserId
     * @param assignUserName
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean batchAssignTasks(List<Long> taskIds, Long assignUserId, String assignUserName) {
        // 检查所有任务状态
        for (Long taskId : taskIds) {
            ErpQualityTask task = baseMapper.selectById(taskId);
            if (task == null || task.getStatus() != 0) {
                throw new RuntimeException("存在非待质检状态的任务，无法批量分配");
            }
        }

        LambdaUpdateWrapper<ErpQualityTask> wrapper = Wrappers.<ErpQualityTask>lambdaUpdate()
            .in(ErpQualityTask::getId, taskIds)
            .set(ErpQualityTask::getAssignUserId, assignUserId)
            .set(ErpQualityTask::getAssignUserName, assignUserName);

        return baseMapper.update(null, wrapper) > 0;
    }

    /**
     * 更新任务优先级
     * @param taskId
     * @param priority
     * @return
     */
    @Override
    public Boolean updatePriority(Long taskId, Integer priority) {
        if (priority < 1 || priority > 3) {
            throw new RuntimeException("优先级参数错误，必须在1-3之间");
        }

        LambdaUpdateWrapper<ErpQualityTask> wrapper = Wrappers.<ErpQualityTask>lambdaUpdate()
            .eq(ErpQualityTask::getId, taskId)
            .set(ErpQualityTask::getPriority, priority);

        return baseMapper.update(null, wrapper) > 0;
    }

    /**
     * 根据BOM到货情况自动创建质检任务
     * @param bomId BOM ID
     * @param bomName BOM名称
     * @return
     */
    //@MonitorMethod(bizType = BizTypeConstant.QUALITY+"Overdue", extractor = QualityDataExtractor.class)
    @Override
    public ErpQualityTask autoCreateQualityTaskByBomArrival(Long bomId, String bomName,String orderNo) {
        log.info("开始为批次 {} 自动创建质检任务", orderNo);
        try {
            // 检查是否已存在该批次的质检任务
            List<ErpQualityTask> existingTasks = baseMapper.selectList(
                Wrappers.<ErpQualityTask>lambdaQuery().eq(ErpQualityTask::getOrderNo, orderNo)
            );

            if (!existingTasks.isEmpty()) {
                log.warn("采购单 {} 已存在质检任务，跳过创建", orderNo);
                return null;
            }

            // 创建质检任务
            ErpQualityTaskBo taskBo = new ErpQualityTaskBo();
            taskBo.setTaskNo(generateTaskNo());
            taskBo.setOrderNo(orderNo);

            taskBo.setBomId(bomId);
            taskBo.setStatus(0); // 待质检
            taskBo.setPriority(1); // 普通优先级
            //taskBo.setTimeoutDuration(5); //默认5天
            taskBo.setRemark("系统自动创建的质检任务");
            taskBo.setCreateBy(LoginHelper.getUsername());
            taskBo.setCreateTime(new Date());
            ErpQualityTask task = insertByBo(taskBo);
            return task;
        } catch (Exception e) {
            log.error("为批次 {} 创建质检任务失败", orderNo, e);
            throw new RuntimeException("创建质检任务失败：" + e.getMessage());
        }
    }

    /**
     * 检查并处理超时任务
     */
    @Override
    public void checkAndHandleTimeoutTasks() {
        List<ErpQualityTask> timeoutTasks = baseMapper.selectList(
            Wrappers.<ErpQualityTask>lambdaQuery()
                .in(ErpQualityTask::getStatus, 0, 1) // 待质检或质检中
                .le(ErpQualityTask::getTimeoutAlarmTime, LocalDateTime.now())
                .eq(ErpQualityTask::getIsTimeout, 0) // 未标记为超时
        );

        if (!timeoutTasks.isEmpty()) {
            log.info("发现 {} 个超时任务，开始处理", timeoutTasks.size());

            for (ErpQualityTask task : timeoutTasks) {
                // 标记为超时
                LambdaUpdateWrapper<ErpQualityTask> wrapper = Wrappers.<ErpQualityTask>lambdaUpdate()
                    .eq(ErpQualityTask::getId, task.getId())
                    .set(ErpQualityTask::getIsTimeout, 1);

                baseMapper.update(null, wrapper);

                log.warn("质检任务 {} 已超时，任务单号：{}", task.getId(), task.getTaskNo());
            }
        }
    }

    /**
     * 生成质检任务单号
     * @return
     */
    @Override
    public String generateTaskNo() {
        String dateStr = DateUtil.format(LocalDateTime.now(), "yyyyMMdd");
        String prefix = "QC" + dateStr;

        // 查询今天已有的最大序号
        LambdaQueryWrapper<ErpQualityTask> wrapper = Wrappers.<ErpQualityTask>lambdaQuery()
            .likeRight(ErpQualityTask::getTaskNo, prefix)
            .orderByDesc(ErpQualityTask::getTaskNo)
            .last("LIMIT 1");

        ErpQualityTask lastTask = baseMapper.selectOne(wrapper);

        int nextSeq = 1;
        if (lastTask != null && lastTask.getTaskNo().startsWith(prefix)) {
            String lastSeqStr = lastTask.getTaskNo().substring(prefix.length());
            try {
                nextSeq = Integer.parseInt(lastSeqStr) + 1;
            } catch (NumberFormatException e) {
                log.warn("解析任务单号序号失败：{}", lastTask.getTaskNo());
            }
        }

        return prefix + String.format("%03d", nextSeq);
    }

    /**
     * 将状态为完成(2)或不合格(3)的任务的超时标记重置为0
     */
    @Override
    public void cleanupCompletedTaskTimeoutFlags() {
        List<ErpQualityTask> timeoutTasks = baseMapper.selectList(
            Wrappers.<ErpQualityTask>lambdaQuery()
                .in(ErpQualityTask::getStatus, 2, 3)
                .le(ErpQualityTask::getTimeoutAlarmTime, LocalDateTime.now())
                .eq(ErpQualityTask::getIsTimeout, 0) // 未标记为超时
        );
        timeoutTasks.forEach(t->{
            t.setIsTimeout(0); //超时标记
            this.baseMapper.updateById(t);
        });
    }

    /**
     *  获取质检项列表
     * @param id
     * @return
     */
    @Override
    public TableDataInfo<ErpPurchaseOrderItemVo> queryQualityItems(Long id) {
        ErpQualityTask qualityTask = this.baseMapper.selectById(id);
        if(LoginHelper.getUserId() != 1 && null != qualityTask.getAssignUserId() &&
            qualityTask.getAssignUserId() != LoginHelper.getUserId()){
            return new TableDataInfo<>();
        }
        String orderNo = qualityTask.getOrderNo();
        TableDataInfo<ErpPurchaseOrderItemVo> page = new TableDataInfo<>();
        List<ErpPurchaseOrderItemVo> erpPurchaseOrderItemVos = purchaseOrderService.queryItemsByOrderNo(orderNo);
        erpPurchaseOrderItemVos.forEach(v->{
            //根据主订单编号查询出子订单
            v.setQcStatus(false);
            QualityRecordQueryDto dto = new QualityRecordQueryDto();
            dto.setTaskId(id);
            dto.setProductId(v.getProductId());
            List<ErpQualityRecordVo>  recordVos = qualityRecordService.queryList(dto);
            for (ErpQualityRecordVo recordVo : recordVos) {
                if (recordVo.getCheckResult() >= 0) {
                    v.setQcStatus(true);
                }
                v.setCheckResult(recordVo.getCheckResult());
                v.setRecordId(recordVo.getId());
            }
        });
        page.setTotal(erpPurchaseOrderItemVos.size());
        page.setCode(200);
        page.setRows(erpPurchaseOrderItemVos);
        return page;
    }

    @Override
    public ErpQualityTaskVo getByOrderNo(String no) {
        return this.baseMapper.selectVoOne(new LambdaQueryWrapper<ErpQualityTask>().eq(ErpQualityTask::getOrderNo,no));
    }

    /**
     * 构建查询条件
     */
    private LambdaQueryWrapper<ErpQualityTask> buildQueryWrapper(QualityTaskQueryDto queryDto) {
        LambdaQueryWrapper<ErpQualityTask> wrapper = Wrappers.lambdaQuery();

        wrapper.like(StringUtils.isNotBlank(queryDto.getTaskNo()), ErpQualityTask::getTaskNo, queryDto.getTaskNo());
        wrapper.like(StringUtils.isNotBlank(queryDto.getOrderNo()), ErpQualityTask::getOrderNo, queryDto.getOrderNo());
        wrapper.eq(ObjectUtil.isNotNull(queryDto.getBomId()), ErpQualityTask::getBomId, queryDto.getBomId());
        wrapper.eq(ObjectUtil.isNotNull(queryDto.getStatus()), ErpQualityTask::getStatus, queryDto.getStatus());
        wrapper.eq(ObjectUtil.isNotNull(queryDto.getPriority()), ErpQualityTask::getPriority, queryDto.getPriority());
        wrapper.eq(ObjectUtil.isNotNull(queryDto.getAssignUserId()), ErpQualityTask::getAssignUserId, queryDto.getAssignUserId());
        wrapper.like(StringUtils.isNotBlank(queryDto.getAssignUserName()), ErpQualityTask::getAssignUserName, queryDto.getAssignUserName());
        wrapper.eq(ObjectUtil.isNotNull(queryDto.getIsTimeout()), ErpQualityTask::getIsTimeout, queryDto.getIsTimeout());

        // 时间范围查询
        if (queryDto.getCreateTimeStart() != null) {
            wrapper.ge(ErpQualityTask::getCreateTime, queryDto.getCreateTimeStart());
        }
        if (queryDto.getCreateTimeEnd() != null) {
            wrapper.le(ErpQualityTask::getCreateTime, queryDto.getCreateTimeEnd());
        }

        // 默认排序：优先级降序，创建时间降序
        wrapper.orderByDesc(ErpQualityTask::getPriority)
            .orderByDesc(ErpQualityTask::getCreateTime);

        return wrapper;
    }

    /**
     * 质检任务审批通过
     * @param taskId
     * @return
     */
    @Override
    public ErpQualityTask approveTask(Long taskId) {
        ErpQualityTask task = this.baseMapper.selectById(taskId);
        if(Objects.nonNull(task)){
            task.setApproveStatus(String.valueOf(ErpAuditStatus.APPROVE.getStatus()));
        }
        this.baseMapper.updateById(task);
        return task;
    }

    /**
     * 质检任务审批拒绝
     * @param taskId
     * @return
     */
    @Override
    public ErpQualityTask rejectTask(Long taskId) {
        ErpQualityTask task = this.baseMapper.selectById(taskId);
        task.setApproveStatus(String.valueOf(ErpAuditStatus.REJECTED.getStatus())); // 3-驳回
        task.setIsOverdue("0");
        int hours = timeoutConfigMapper.getTimeByBizType(BizTypeConstant.SOLUTION);
        task.setIsOverdueEndTime(LocalDateTime.now().plusHours(hours));

        this.baseMapper.updateById(task);
        return task;
    }

    /**
     * 提交质检任务
     * @param id
     * @return
     */
    @Override
    public ErpQualityTask respondOrder(Long id,Integer days) {
        ErpQualityTask task = this.baseMapper.selectById(id);
        task.setUpdateBy(LoginHelper.getUsername());
        task.setApproveStatus(String.valueOf(ErpAuditStatus.SUBMITTED.getStatus()));
        task.setIsOverdue(OverdueStatus.PROCESSED);
        task.setEstimatedHours(days);
        task.setTaskDeadline(LocalDateTime.now().plusDays(days));

        if(task.getIsOverdueEndTime().isBefore(LocalDateTime.now())){
            task.setIsOverdue(OverdueStatus.OVERDUE_AND_PROCESSED);
        }
        //任务截止时间
        this.baseMapper.updateById(task);

        //发起工作流
        StartProcessDTO process = new StartProcessDTO();
        Map<String,Object> map = new HashMap<>();
        map.put("type","quality");
        process.setVariables(map);
        process.setFlowCode("qualityTask");
        process.setBusinessId(String.valueOf(task.getId()));
        StartProcessReturnDTO processReturnDTO = workflowService.startWorkFlow(process);
        log.info("流程审批发起成功，已启动: projectId={}, engineerId={}", id, LoginHelper.getUsername());
        workflowService.completeTask(processReturnDTO.getTaskId(),"完成该质检任务所需时长1天");
        return null;
    }

    /**
     * 修改质检时长
     * @param id
     * @param days
     * @return
     */
    @Override
    public ErpQualityTask submitDays(Long id, Integer days) {
        ErpQualityTask task = this.baseMapper.selectById(id);
        task.setEstimatedHours(days);
        task.setTaskDeadline(LocalDateTime.now().plusDays(days));

        if(task.getIsOverdueEndTime().isBefore(LocalDateTime.now())){
            task.setIsOverdue(OverdueStatus.OVERDUE_AND_PROCESSED);
        }
        task.setStatus(Integer.valueOf(OverdueStatus.PROCESSED));
        this.baseMapper.updateById(task);
        return task;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(ErpQualityTask entity) {
        if (ObjectUtil.isNull(entity.getStatus())) {
            entity.setStatus(0); // 默认待质检
        }
        if (ObjectUtil.isNull(entity.getPriority())) {
            entity.setPriority(1); // 默认普通优先级
        }
//        if (ObjectUtil.isNull(entity.getTimeoutDuration())) {
//            entity.setTimeoutDuration(240); // 默认4小时
//        }
        if (ObjectUtil.isNull(entity.getIsTimeout())) {
            entity.setIsTimeout(0); // 默认未超时
        }
    }

    /**
     * 保存时效配置表中
     * @param task
     */
    private void insertTimeInstance(ErpQualityTask task){
        TimeoutInstance instance = new TimeoutInstance();
        TimeoutInstance ti = timeoutInstanceService.getOne(new LambdaQueryWrapper<TimeoutInstance>()
            .eq(TimeoutInstance::getBizId, task.getId()));
        if(Objects.nonNull(ti)){
            instance.setId(ti.getId());
        }
        instance.setBizName(task.getOrderNo()+"-质检/组装");
        instance.setBizId(task.getId());
        instance.setCompletionTime(task.getCompleteTime());
        instance.setRemindTime(task.getTimeoutAlarmTime());
        instance.setDeadlineTime(task.getTimeoutAlarmTime());
        instance.setTimeoutReason(task.getRemark());
        instance.setExtendReason(task.getRemark());
        instance.setStatus(BizTypeConstant.WAITING);
        if (QualityTaskConstants.Status.COMPLETED.equals(task.getStatus()) ||
            QualityTaskConstants.Status.FAILED.equals(task.getStatus())) {
            instance.setStatus(BizTypeConstant.COMPLETED);
        }
        instance.setBizType(BizTypeConstant.QUALITY);
        instance.setCreateBy(LoginHelper.getUsername());
        instance.setTriggerTime(LocalDateTime.now());
        instance.setTenantId(LoginHelper.getTenantId());
        SysUserVo sysUserVo = userService.selectUserByUserName(task.getAssignUserName());
        if(Objects.nonNull(sysUserVo)){
            instance.setUpdateBy(sysUserVo.getNickName());
        }
        timeoutInstanceService.saveOrUpdate(instance);

    }
}
